//
//  MCRechargeViewController.m
//  TLYL
//
//  Created by MC on 2017/6/13.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCRechargeViewController.h"
#import "MCRechargeDetailViewController.h"
#import "MCMineCellModel.h"
#import "MCRechargeHeaderView.h"
#import "MCRechargeFooterView.h"
#import "MCRechargeTableViewCell.h"
#import "MCRechargeModel.h"
#import "MCUserMoneyModel.h"
#import "ExceptionView.h"
#import "MCPopAlertView.h"
#import "MCPaySelectedLotteryPickView.h"
#import "MCDataTool.h"
#import "MCWechatRechargeVC.h"
#import "MCGroupPaymentNewModel.h"
/*
 65:扫码付(wechat)
 66:扫码付(qqpay)
 67:扫码付(alipay)
 */
#define Tip1 @"温馨提示：\n尊敬的会员您好，该通道支付充值，凡是10的倍数的金额会加0.01，例如您充值100元，会变成充值100.01，您支付成功也是100.01，上分也是100.01；目的是为了提高充值成功率。谢谢合作！"

/*
 *  68:扫码付(网银)
 */
#define Tip2 @""//扫码付单笔限额提醒：\n1、工商银行，农业银行，建设银行，中国银行，光大银行，上海银行，招商银行，民生银行，邮政储蓄银行，平安银行，中信银行：单笔限额为 [50-50000].\n2、华夏银行，兴业银行，交通银行，浦发银行：单笔限额为 [1000-50000].\n3、广发银行，北京银行：单笔限额为 [350-50000].


@interface MCRechargeViewController ()
<
UITextFieldDelegate,
UITableViewDelegate,
UITableViewDataSource,
MCRechargeFooterDelegate,
MCRechargeTypeDelegate
>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray*sectionMarr;
@property(nonatomic, strong)MCRechargeHeaderView * headerView;
@property(nonatomic, strong)MCRechargeFooterView * footerView;
@property(nonatomic, strong)UITextField  * textField;
@property(nonatomic, strong)MCPaymentNewModel *selectedModel;

/*
 * Api模型
 */
/**获取用户组充值方式*/
@property(nonatomic, strong)MCGroupPaymentNewModel * groupPayment_NewModel;
/**添加充值信息*/
@property(nonatomic, strong)MCRechargeModel     * rechargeModel;
/**查询用户余额及冻结金额*/
@property(nonatomic, strong)MCUserMoneyModel    * userMoneyModel;


@property(nonatomic, strong)ExceptionView * exceptionView;
@property(nonatomic, strong)MCRechargeTableViewCell *ex_cell;


@end

@implementation MCRechargeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setProperty];
    
    [self createUI];
    
    [self loadData];
    
    
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //    [BKIndicationView dismiss];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;
    /*
     * 重新加载余额
     */
    MCUserMoneyModel * userMoneyModel=[MCUserMoneyModel sharedMCUserMoneyModel];
    [userMoneyModel refreashDataAndShow];
    self.userMoneyModel=userMoneyModel;
    self.headerView.dataSource=userMoneyModel.LotteryMoney;
    
    __weak __typeof(self)wself = self;
    
    userMoneyModel.callBackSuccessBlock = ^(id manager) {
        
        wself.userMoneyModel.FreezeMoney=manager[@"FreezeMoney"];
        wself.userMoneyModel.LotteryMoney=manager[@"LotteryMoney"];
        wself.headerView.dataSource=manager[@"LotteryMoney"];
    };
    
}


#pragma mark==================setProperty======================
-(void)setProperty{
    
    self.view.backgroundColor=RGB(231, 231, 231);
    self.title=@"充值";
    _sectionMarr= [[NSMutableArray alloc]init];
    _selectedModel=[[MCPaymentNewModel alloc]init];
}

#pragma mark==================createUI======================
-(void)createUI{
    __weak __typeof__ (self) wself = self;
    
    [self.view addSubview:self.headerView];
    self.headerView.frame=CGRectMake(0, 0, G_SCREENWIDTH, [MCRechargeHeaderView computeHeight:nil]);
    self.headerView.shuaXinBlock = ^{
        
        //刷新余额
        [BKIndicationView showInView:wself.view];
        MCUserMoneyModel * userMoneyModel=[MCUserMoneyModel sharedMCUserMoneyModel];
        [userMoneyModel refreashDataAndShow];
        wself.userMoneyModel=userMoneyModel;
        userMoneyModel.callBackSuccessBlock = ^(id manager) {
            [BKIndicationView dismiss];
            wself.userMoneyModel.FreezeMoney=manager[@"FreezeMoney"];
            wself.userMoneyModel.LotteryMoney=manager[@"LotteryMoney"];
            wself.headerView.yuElab.text = [MCMathUnits GetMoneyShowNum:manager[@"LotteryMoney"]];
            
        };
        
        userMoneyModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
            [BKIndicationView dismiss];
        };
    };
    
    [self.view addSubview:self.tableView];
    _tableView.frame=CGRectMake(0, [MCRechargeHeaderView computeHeight:nil], G_SCREENWIDTH, G_SCREENHEIGHT-[MCRechargeHeaderView computeHeight:nil]);
    
    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.cancelsTouchesInView = NO;
    [_tableView addGestureRecognizer:singleTapGesture];
    
    
}
#pragma mark - gesture actions
- (void)closeKeyboard:(UITapGestureRecognizer *)recognizer {
    [self.view endEditing:YES];
}


#pragma mark==================loadData======================
-(void)loadData{
    
    
    [BKIndicationView showInView:self.view];
    
    __weak __typeof__ (self) wself = self;
    
    MCGroupPaymentNewModel * groupPayment_NewModel = [[MCGroupPaymentNewModel alloc]init];
    self.groupPayment_NewModel = groupPayment_NewModel;
    
    [groupPayment_NewModel refreashDataAndShow];
    __weak MCGroupPaymentNewModel *weakNewModel_Self = groupPayment_NewModel;
    groupPayment_NewModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        
        wself.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
        wself.exceptionView.originY=kStatusBarAndNavigationBarHeight;
        ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
            [wself.exceptionView dismiss];
            wself.exceptionView = nil;
            [wself loadData];
        }];
        [wself.exceptionView addAction:action];
        [wself.exceptionView showInView:wself.view];
        
        
    };
    groupPayment_NewModel.callBackSuccessBlock = ^(ApiBaseManager *manager) {
        
        NSDictionary * dic = manager.ResponseRawData;
        
        [weakNewModel_Self setPayMentArrWithData:dic];
        
        if ([self.groupPayment_NewModel.AllRecMethod count]<1) {
            
            //            [SVProgressHUD showInfoWithStatus:@"您的账号暂不支持充值!"];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeCannotRecharge];
            self.exceptionView.originY=kStatusBarAndNavigationBarHeight;
            [self.exceptionView showInView:wself.view];
            
            return;
        }
        
        [wself reloadData];
        
    };
    
    
    
    
}


-(void)reloadData{
    
    [_sectionMarr removeAllObjects];
    NSMutableArray * marr_Model=[[NSMutableArray alloc]init];
    
    CellModel* model1 =[[CellModel alloc]init];
    model1.reuseIdentifier = NSStringFromClass([MCRechargeTableViewCell class]);
    model1.className=NSStringFromClass([MCRechargeTableViewCell class]);
    model1.height = [MCRechargeTableViewCell computeHeight:self.groupPayment_NewModel.payMentArr.count];
    model1.selectionStyle=UITableViewCellSelectionStyleNone;
    model1.accessoryType=UITableViewCellAccessoryNone;
    
    /*
     * 传递参数
     */
    //默认第一个选中
    MCPayTypeModel * big_model = self.groupPayment_NewModel.AllRecMethod[0];
    big_model.isSelected=YES;
    model1.userInfo=self.groupPayment_NewModel.AllRecMethod;
    if (self.groupPayment_NewModel.AllRecMethod.count>0) {
        [marr_Model addObject:model1];
    }
    
    
    SectionModel *model_Section=[SectionModel sectionModelWithTitle:@"" cells:marr_Model];
    model_Section.headerhHeight=0.0001;
    model_Section.footerHeight=[MCRechargeFooterView computeHeight:nil];
    
    [_sectionMarr addObject:model_Section];
    
    [_tableView reloadData];
    
}


#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _sectionMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _sectionMarr[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _sectionMarr[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _sectionMarr[section];
    return sm.footerHeight;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return self.footerView;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _sectionMarr[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _sectionMarr[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = cm.selectionStyle;
    
    
    if([cm.className isEqualToString:NSStringFromClass([MCRechargeTableViewCell class])]){
        MCRechargeTableViewCell *ex_cell=(MCRechargeTableViewCell *)cell;
        _textField=ex_cell.textField;
        _textField.delegate=self;
        ex_cell.delegate=self;
        _ex_cell=ex_cell;
        _ex_cell.selectedModel = _selectedModel;
        if (cm.userInfo) {
            ex_cell.dataSource=cm.userInfo;
        }
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-Header
-(MCRechargeHeaderView *)headerView{
    if (!_headerView) {
        _headerView =[[MCRechargeHeaderView alloc]init];
    }
    return _headerView;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
#pragma mark-Footer
-(MCRechargeFooterView *)footerView{
    if (!_footerView) {
        _footerView =[[MCRechargeFooterView alloc]init];
        _footerView.delegate=self;
    }
    return _footerView;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [_textField resignFirstResponder];
}


#pragma mark-MCRechargeFooterDelegate /确认充值/
-(void)performRecharge{
    if (_selectedModel.BankList.count>0) {
        
        [self bankSelectedBtnClick];
        
    }else{
        
        [self DoPay];
        
    }
    
}

-(void)DoPay{
    
    _selectedModel.RechargeMoney=_textField.text;
    
    
    if (_selectedModel.RechargeMoney==nil||[_selectedModel.RechargeMoney isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入充值金额！"];
    }
    
    
    
    float money= [_textField.text floatValue];
    
    if (money<[_selectedModel.MinRecMoney intValue]||money>[_selectedModel.MaxRecMoney intValue]) {
        
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"充值金额范围%@~%@",_selectedModel.MinRecMoney,_selectedModel.MaxRecMoney]] ;
        return;
        
    }
    if (!_selectedModel.PayInType||_selectedModel.PayInType==nil) {
        [SVProgressHUD showErrorWithStatus:@"请选择充值方式"] ;
        return;
    }
    
    //    PayTypeId    是    String    充值大类ID
    //    PayTypeName    是    String    充值大类名称
    //    PayName    是    String    充值小类 名称
    
    NSDictionary * dic=@{
                         @"RechargeMoney":_selectedModel.RechargeMoney,
                         @"BankCode":_selectedModel.BankCode,
                         @"RechargeType":_selectedModel.PayInType,
                         @"PayTypeId":_selectedModel.ID,
                         @"PayTypeName":_selectedModel.ClientPayTypeName,
                         @"PayName":_selectedModel.RealPayName,
                         @"FeeType":_selectedModel.FeeType,
                         @"FeeMoney":_selectedModel.FeeMoney,
                         @"CappingMoney":_selectedModel.CappingMoney
                
                         };
    
    
    MCRechargeModel     * rechargeModel = [[MCRechargeModel alloc]initWithDic:dic];
    self.rechargeModel = rechargeModel;
    [BKIndicationView showInView:self.view];
    [rechargeModel refreashDataAndShow];
    
    
    
    rechargeModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        
        //   [MBProgressHUD showError:@"服务器链接失败" toView:self.view];
        
    };
    
    
    
    __weak __typeof__ (self) wself = self;
    
    rechargeModel.callBackSuccessBlock = ^(id manager) {
        
        MCRechargeModel *dataSource=[[MCRechargeModel alloc]init];
        dataSource = [MCRechargeModel mj_objectWithKeyValues:manager];
        
        
//        MCPopAlertView *mcAlertView = [[MCPopAlertView alloc] initWithType:MCPopAlertTypeCZRequest_Confirm Title:@"支付确认" leftBtn:@"前往支付" rightBtn:@"取消返回" RechargeModel:dataSource];
//
//        mcAlertView.resultIndex = ^(NSInteger index){
//            if (index==1) {
//
        
                /*
                 * 跳转微信扫码付
                 */
                if ([_selectedModel.PayInType isEqualToString:@"118"]) {
                    
                    MCWechatRechargeVC * VC = [[MCWechatRechargeVC alloc]init];
                    VC.rechargeModel=dataSource;
                    [wself.navigationController pushViewController:VC animated:YES];
                    return ;
                    
                }
                
                
                
                MCRechargeDetailViewController * vc=[[MCRechargeDetailViewController alloc]init];
                vc.dataSource=dataSource;
                if (dataSource.PayBank.length<1) {
                    vc.dataSource.PayBank=wself.selectedModel.PayName;
                }
                if ([dataSource.PType integerValue]==15) {
                }else{
                    if (wself.selectedModel.PayName.length>0) {
                        vc.dataSource.PayBank=wself.selectedModel.PayName;
                    }
#pragma mark-直接跳转付款
                    //                    //直接跳转付款
                    //                    [wself payToWebWithMCRechargeModel:dataSource];
                    //                    return;
                }
                
                
                //                vc.dataSource.PayMoney=wself.selectedModel.RechargeMoney;
                vc.dataSource.PayMoney=dataSource.PayMoney;
                vc.dataSource.BankCode=_selectedModel.BankCode;
                [wself.navigationController pushViewController:vc animated:YES];
//            }
//        };
//        [mcAlertView showXLAlertView];
    
        /*
         * 开户行的显示规则是这样的：在 add_recharge_info 这个接口中，会返回 PayBank 这个字段，这个字段可能有3种情况，一种为空（针对在线充值类），一种只包含“收款银行”，一种同时包含了“收款银行”和“开户银行”。
         举例如下： PayBank:"工商银行,安徽阜阳"，逗号前为收款银行，逗号后为开户银行。
         程序中逻辑为：①判断是否有逗号，有则用逗号分隔，无则直接赋值为“收款银行”；②有逗号，则分隔后取下标为0的作为“收款银行”；③下标为1的判断是否有值，有则显示到“开户银行”，无则不显示。（因为有的时候会返回“工商银行, ”这样的字段）
         */
        
    };
    
    
    
}




#pragma mark-MCRechargePaymentTypeDelegate  /选择付款方式/
-(void)celldidSelectPaymentType:(MCPaymentNewModel *)type{
    
    NSLog(@"------选择付款方式---------%@-",type.PayName);
    
    _selectedModel.PayName=type.PayName;
    _selectedModel.RealPayName=type.RealPayName;
    _selectedModel.Order=type.Order;
    _selectedModel.SysId=type.SysId;
    _selectedModel.MinRecMoney=type.MinRecMoney;
    _selectedModel.MaxRecMoney=type.MaxRecMoney;
    _selectedModel.BankCode=type.BankCode;
    _selectedModel.PayInType=type.PayInType;
    _selectedModel.BankList=type.BankList;
    _selectedModel.logoType=type.logoType;
    _selectedModel.PicCode=type.PicCode;
    _selectedModel.ID=type.ID;
    _selectedModel.ClientPayTypeName = type.ClientPayTypeName;
    _selectedModel.FeeType = type.FeeType;
    _selectedModel.FeeMoney = type.FeeMoney;
    _selectedModel.CappingMoney = type.CappingMoney;

    _ex_cell.selectedModel = _selectedModel;
    
    
    //    230. 231.  232
    //
    if ([type.PayInType isEqualToString:@"230"]||[type.PayInType isEqualToString:@"231"]||[type.PayInType isEqualToString:@"232"]) {
//     需求：2018年09月17日   充值：[id 230、231、232]的支付，充值金额去掉固定额度，改为手动输入。
//        [_ex_cell setUIIsWechatAndAliPay:YES];
    }else{
        [_ex_cell setUIIsWechatAndAliPay:NO];
    }
    
//    if([type.PayInType isEqualToString:@"65"]||[type.PayInType isEqualToString:@"66"]||[type.PayInType isEqualToString:@"67"]){
//        [_footerView setLabelSpace:_footerView.lab_tip withValue:Tip1 withFont:[UIFont systemFontOfSize:10]];
//    }else if([type.PayInType isEqualToString:@"68"]){
//        [_footerView setLabelSpace:_footerView.lab_tip withValue:Tip2 withFont:[UIFont systemFontOfSize:10]];
//    }else{
//        _footerView.lab_tip.text=@"";
//    }
    [_ex_cell caculateSXF];
}


#pragma mark-MCRechargePayMoneyDelegate  /选择金额/
-(void)celldidSelectChooseMoney:(id)money{
    
    NSLog(@"------选择金额---------%@",money);

    _textField.text=[NSString stringWithFormat:@"%d",[money intValue]];
    _selectedModel.RechargeMoney=_textField.text;
    [_ex_cell.btn_SearchMoney setTitle:[NSString stringWithFormat:@"%d",[money intValue]] forState:UIControlStateNormal];
    [_ex_cell.btn_SearchMoney setTitleColor:RGB(46, 46, 46) forState:UIControlStateNormal];
    [_ex_cell caculateSXF];
}

#pragma mark-银行选择
- (void)bankSelectedBtnClick{
    __weak __typeof__ (self) wself = self;
    NSDictionary * dicB=[MCDataTool MC_GetDic_Bank];
    NSMutableArray * marr=[[NSMutableArray alloc]init];
    for (NSDictionary * item in _selectedModel.BankList) {
        //　　　　　　　　　　　　　　　　　　　　"BankCode":"CMB",
        //　　　　　　　　　　　　　　　　　　　　"PayBankCode":"308584000013",
        //　　　　　　　　　　　　　　　　　　　　"BankName":"招商银行",
        //　　　　　　　　　　　　　　　　　　　　"Order":"1"
        
        MCBankModel * model=[[MCBankModel alloc]init];
        NSString * BankCode = item[@"BankCode"];
        NSString * BankName = item[@"BankName"];
        model.bankId=BankCode;
        model.bankLogo=dicB[BankCode][@"logo"];
        model.bankName=BankName;
        //        model.bankName=dicB[BankCode][@"name"];
        [marr addObject:model];
    }
    //    for (NSString * item in _selectedModel.arr_FastPayment) {
    //        MCBankModel * model=[[MCBankModel alloc]init];
    //        model.bankId=item;
    //        model.bankLogo=dicB[item][@"logo"];
    //        model.bankName=dicB[item][@"name"];
    //        [marr addObject:model];
    //    }
    
    MCPaySelectedLotteryPickView *picker = [[MCPaySelectedLotteryPickView alloc]init];
    picker.dataSource =marr;
    picker.title=@"请选择支付方式";
    picker.Type=MCPaySelectedPickViewType_FastPay;
    picker.getBankBlock = ^(MCBankModel *t) {
        wself.selectedModel.BankCode=t.bankId;
        [wself DoPay];
    };
    [picker show];
    
    
}


@end
















































